import Vue from 'vue'
import VueRouter from 'vue-router'

// import Login from '@/views/Login'
// import Reg from '@/views/Reg'
// import Layout from '@/views/Layout'
// import Home from '@/views/Home'
// import ArtCategory from '@/views/ArtCategory'
// import ArtList from '@/views/ArtList'
// import UserInfo from '@/views/UserInfo'
// import ChangeAvatar from '@/views/ChangeAvatar'
// import ResetPwd from '@/views/ResetPwd'

const Login = () => import('@/views/Login')
const Reg = () => import('@/views/Reg')
const Layout = () => import('@/views/Layout')
const Home = () => import('@/views/Home')
const ArtCategory = () => import('@/views/ArtCategory')
const ArtList = () => import('@/views/ArtList')
const UserInfo = () => import('@/views/UserInfo')
const ChangeAvatar = () => import('@/views/ChangeAvatar')
const ResetPwd = () => import('@/views/ResetPwd')

// const Login = () => import('@/views/Login') // 单独加载login对应的文件
Vue.use(VueRouter)

const router = new VueRouter({

  // hash #
  // history 不带# + 上线 服务端配置(node)
  // mode: 'history',
  mode: 'hash',
  routes: [
    {
      path: '/',
      component: Layout,
      children: [
        // Layout组件的默认显示子组件是Home
        { path: '/', component: Home },
        { path: '/artcategory', component: ArtCategory },
        { path: '/artlist', component: ArtList },
        { path: '/userinfo', component: UserInfo },
        { path: '/changeavatar', component: ChangeAvatar },
        { path: '/resetpwd', component: ResetPwd }
      ]
    },
    {
      name: 'login',
      path: '/login',
      component: Login
    },
    {
      name: 'reg',
      path: '/reg',
      component: Reg
    }
  ]
})

// to => 要显示的路由配置对象  to.path
// from => 当前显示的路由配置对象  from.path
// next => 函数 next() => 继续执行路由匹配 => 显示组件

router.beforeEach((to, from, next) => {
  // 要去的是登录或者注册 => next()
  if (to.path === '/login' || to.path === '/reg') {
    next()
  } else {
    // 反之 => 验证 => 是否有token => next()
    if (window.localStorage.getItem('token')) {
      next()
    } else {
      next({ path: '/login' })
    }
  }
})
export default router
